package com.sky.lightleafpicturepavilionserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.lightleafpicturepavilionserver.domain.Wallpaper;
import com.sky.lightleafpicturepavilionserver.domain.WallpaperCategory;
import com.sky.lightleafpicturepavilionserver.dto.WallpaperCategoryDTO;
import com.sky.lightleafpicturepavilionserver.dto.WallpaperCategoryDetailDTO;
import com.sky.lightleafpicturepavilionserver.dto.WallpaperCategoryPageDTO;
import com.sky.lightleafpicturepavilionserver.mapper.WallpaperMapper;
import com.sky.lightleafpicturepavilionserver.mapper.WallpaperCategoryMapper;
import com.sky.lightleafpicturepavilionserver.service.WallpaperCategoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【wallpaper_category(壁纸分类表)】的数据库操作Service实现
* @createDate 2025-09-30 20:16:58
*/
@Slf4j
@Service
public class WallpaperCategoryServiceImpl extends ServiceImpl<WallpaperCategoryMapper, WallpaperCategory>
    implements WallpaperCategoryService {

    @Resource
    private WallpaperMapper wallpaperMapper;

    /**
     * 获取启用的分类列表（用于首页展示）
     */
    @Override
    public List<WallpaperCategoryDTO> getEnabledCategoryList() {
        log.info("获取启用的分类列表");
        
        LambdaQueryWrapper<WallpaperCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WallpaperCategory::getStatus, 1)  // 只查询启用的分类
                .orderByAsc(WallpaperCategory::getSortOrder)  // 按排序权重升序（数值越小越靠前）
                .orderByDesc(WallpaperCategory::getCreateTime);  // 再按创建时间降序
        
        List<WallpaperCategory> categoryList = this.list(queryWrapper);
        
        // 转换为DTO并统计壁纸数量
        List<WallpaperCategoryDTO> result = categoryList.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        log.info("获取到{}个启用的分类", result.size());
        return result;
    }

    /**
     * 分页查询分类列表
     */
    @Override
    public Page<WallpaperCategoryDTO> getCategoryPage(WallpaperCategoryPageDTO pageDTO) {
        log.info("分页查询分类列表，参数：{}", pageDTO);
        
        Page<WallpaperCategory> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        
        LambdaQueryWrapper<WallpaperCategory> queryWrapper = new LambdaQueryWrapper<>();
        
        // 分类名称模糊查询
        if (StringUtils.hasText(pageDTO.getName())) {
            queryWrapper.like(WallpaperCategory::getName, pageDTO.getName());
        }
        
        // 状态筛选
        if (pageDTO.getStatus() != null) {
            queryWrapper.eq(WallpaperCategory::getStatus, pageDTO.getStatus());
        }
        
        queryWrapper.orderByAsc(WallpaperCategory::getSortOrder)  // 按排序权重升序
                .orderByDesc(WallpaperCategory::getCreateTime);  // 再按创建时间降序
        
        Page<WallpaperCategory> categoryPage = this.page(page, queryWrapper);
        
        // 转换为DTO分页结果
        Page<WallpaperCategoryDTO> result = new Page<>();
        result.setCurrent(categoryPage.getCurrent());
        result.setSize(categoryPage.getSize());
        result.setTotal(categoryPage.getTotal());
        result.setPages(categoryPage.getPages());
        
        List<WallpaperCategoryDTO> dtoList = categoryPage.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        result.setRecords(dtoList);
        
        log.info("分页查询完成，共{}条记录", result.getTotal());
        return result;
    }

    /**
     * 获取分类详情
     */
    @Override
    public WallpaperCategoryDetailDTO getCategoryDetail(Long categoryId) {
        log.info("获取分类详情，分类ID：{}", categoryId);
        
        WallpaperCategory category = this.getById(categoryId);
        if (category == null) {
            log.warn("分类不存在，分类ID：{}", categoryId);
            return null;
        }
        
        // 统计该分类下的壁纸数量
        LambdaQueryWrapper<Wallpaper> wallpaperQuery = new LambdaQueryWrapper<>();
        wallpaperQuery.eq(Wallpaper::getCategoryId, categoryId)
                .eq(Wallpaper::getStatus, 1);  // 只统计启用的壁纸
        long wallpaperCount = wallpaperMapper.selectCount(wallpaperQuery);
        
        // 统计该分类下的热门壁纸数量
        LambdaQueryWrapper<Wallpaper> hotWallpaperQuery = new LambdaQueryWrapper<>();
        hotWallpaperQuery.eq(Wallpaper::getCategoryId, categoryId)
                .eq(Wallpaper::getStatus, 1)
                .eq(Wallpaper::getIsHot, 1);  // 热门壁纸
        long hotWallpaperCount = wallpaperMapper.selectCount(hotWallpaperQuery);
        
        WallpaperCategoryDetailDTO result = WallpaperCategoryDetailDTO.builder()
                .id(category.getId())
                .name(category.getName())
                .description(category.getDescription())
                .iconUrl(category.getIconUrl())
                .coverUrl(category.getCoverUrl())
                .wallpaperCount((int) wallpaperCount)
                .hotWallpaperCount((int) hotWallpaperCount)
                .build();
        
        log.info("获取分类详情完成，分类：{}，壁纸数量：{}，热门壁纸数量：{}", 
                category.getName(), wallpaperCount, hotWallpaperCount);
        return result;
    }

    /**
     * 获取热门分类列表（按壁纸数量和排序权重排序）
     */
    @Override
    public List<WallpaperCategoryDTO> getHotCategoryList(Integer limit) {
        log.info("获取热门分类列表，限制数量：{}", limit);
        
        LambdaQueryWrapper<WallpaperCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WallpaperCategory::getStatus, 1)  // 只查询启用的分类
                .orderByAsc(WallpaperCategory::getSortOrder)  // 按排序权重升序
                .orderByDesc(WallpaperCategory::getCreateTime);  // 再按创建时间降序
        
        if (limit != null && limit > 0) {
            queryWrapper.last("LIMIT " + limit);
        }
        
        List<WallpaperCategory> categoryList = this.list(queryWrapper);
        
        // 转换为DTO并按壁纸数量排序
        List<WallpaperCategoryDTO> result = categoryList.stream()
                .map(this::convertToDTO)
                .sorted((a, b) -> {
                    // 先按壁纸数量降序，再按排序权重升序
                    int countCompare = b.getWallpaperCount().compareTo(a.getWallpaperCount());
                    if (countCompare != 0) {
                        return countCompare;
                    }
                    return a.getSortOrder().compareTo(b.getSortOrder());
                })
                .collect(Collectors.toList());
        
        log.info("获取到{}个热门分类", result.size());
        return result;
    }

    /**
     * 实体转DTO
     */
    private WallpaperCategoryDTO convertToDTO(WallpaperCategory category) {
        // 统计该分类下的壁纸数量
        LambdaQueryWrapper<Wallpaper> wallpaperQuery = new LambdaQueryWrapper<>();
        wallpaperQuery.eq(Wallpaper::getCategoryId, category.getId())
                .eq(Wallpaper::getStatus, 1);  // 只统计启用的壁纸
        long wallpaperCount = wallpaperMapper.selectCount(wallpaperQuery);
        
        return WallpaperCategoryDTO.builder()
                .id(category.getId())
                .name(category.getName())
                .description(category.getDescription())
                .iconUrl(category.getIconUrl())
                .coverUrl(category.getCoverUrl())
                .sortOrder(category.getSortOrder())
                .wallpaperCount((int) wallpaperCount)
                .build();
    }
}




